import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from libs.conn import get_config
from libs.utils import is_valid_email, is_valid_emails

# 邮件服务器配置
# SMTP_SERVER = "smtp.qq.com"  # SMTP服务器地址（如Gmail是smtp.gmail.com）
# SMTP_PORT = 587                  # SMTP端口（通常为587或465）
# EMAIL = "" # 发送方邮箱
# PASSWORD = ""       # 邮箱密码或授权码


# 构造邮件
def send_email(recipient, subject, body):
    SMTP_SERVER = get_config('email_smtp_server')  # SMTP服务器地址（如Gmail是smtp.gmail.com）
    SMTP_PORT = int(get_config('email_smtp_port'))     # SMTP端口（通常为587或465）
    EMAIL = get_config('email_sender_address') # 发送方邮箱
    PASSWORD = get_config('email_sender_password')       # 邮箱密码或授权码
    return send_email_with_config(recipient, subject, body, {'email_smtp_server': SMTP_SERVER, 'email_smtp_port': SMTP_PORT, 'email_sender_address': EMAIL, 'email_sender_password': PASSWORD})

def send_email_with_config(recipient, subject, body, config):
    try:
        SMTP_SERVER = config['email_smtp_server']  # SMTP服务器地址（如Gmail是smtp.gmail.com）
        SMTP_PORT = config['email_smtp_port']      # SMTP端口（通常为587或465）
        EMAIL = config['email_sender_address'] # 发送方邮箱
        PASSWORD = config['email_sender_password']       # 邮箱密码或授权码
        if not is_valid_emails(recipient):
            print('无效的邮箱地址：', recipient)
            return False, '无效的邮箱地址：' + recipient
        if not is_valid_email(EMAIL):
            print('无效的邮箱地址：', EMAIL)
            return False, '无效的邮箱地址：' + EMAIL
        print('发送邮件：', recipient, subject, body, config)
        # 创建多部分邮件对象
        msg = MIMEMultipart()
        msg["From"] = EMAIL
        msg["To"] = recipient
        msg["Subject"] = subject
        # msg["Cc"] = '' # 抄送，咱不实现
        
        # 邮件正文
        msg.attach(MIMEText(body, "plain"))
        
        # 连接SMTP服务器
        with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
            server.starttls()  # 启用安全传输
            server.login(EMAIL, PASSWORD)
            server.sendmail(EMAIL, recipient, msg.as_string())
            print("邮件发送成功")
            return True, "邮件发送成功"

    except smtplib.SMTPResponseException as e:
        print(f"SMTP响应异常: {e}") # 但是能发送邮件，所以返回True
        return True, "邮件发送成功"
    except Exception as e:
        print(f"邮件发送失败: {e}")
        return False, str(e)

if __name__ == "__main__":
    # 使用示例
    send_email("2825532618@qq.com", "测试邮件", "这是一封测试邮件。")
